package cc.spider.web.parser;

import org.jsoup.nodes.Document;
import org.seimicrawler.xpath.JXDocument;
import org.seimicrawler.xpath.JXNode;
import org.seimicrawler.xpath.exception.XpathSyntaxErrorException;

import java.util.ArrayList;
import java.util.List;

/**
 * 还没写完
 * @deprecated
 */
public class JsoupXpathParser implements ISelector {
    private JXDocument jxDocument;
    private String content;
    private String baseUrl;

    public JsoupXpathParser(String content, String baseUrl) {
        this.content = content;
        this.baseUrl = baseUrl;
        Document doc = new Document(baseUrl);
        doc.html(content);
        jxDocument = JXDocument.create(doc);
    }

    @Override
    public JsoupXpathParser query(String selector) {
        try {
            JXNode jxNode = jxDocument.selNOne(selector);
            return new JsoupXpathParser(jxNode.getElement().outerHtml(), this.baseUrl);
        } catch (XpathSyntaxErrorException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<JsoupXpathParser> queryAll(String selector) {
        try {
            List<JXNode> jxNodeList = jxDocument.selN(selector);
            List<JsoupXpathParser> selectorList = new ArrayList<>();
            for (JXNode jxNode : jxNodeList) {
                selectorList.add(new JsoupXpathParser(jxNode.getElement().outerHtml(), this.baseUrl));
            }
            return selectorList;
        } catch (XpathSyntaxErrorException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<JsoupXpathParser> children() {
       return this.children("/");
    }

    @Override
    public List<JsoupXpathParser> children(String selector) {
        try {
            List<JXNode> jxNodeList = jxDocument.selN(selector);
            List<JsoupXpathParser> selectorList = new ArrayList<>();
            for (JXNode jxNode : jxNodeList) {
                selectorList.add(new JsoupXpathParser(jxNode.getElement().children().outerHtml(), this.baseUrl));
            }
            return selectorList;
        } catch (XpathSyntaxErrorException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String content(){
       return this.content;
    }
}
